package com.example.orderprovider.config;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class OrderRabbitConfig {
    // 定义普通正常的交换机
    private final String ORDER_EXCHANGE = "order_exchange";
    // 定义普通正常的队列
    private final String ORDER_QUEUE = "order_queue";

    // 定义死信过期过期的交换机
    private final String EXPIRE_EXCHANGE = "expire_exchange";
    // 定义死信过期过期的队列
    private final String EXPIRE_QUEUE = "expire_queue";

    // 死信过期交换机
    @Bean(EXPIRE_EXCHANGE)
    public Exchange expireExchange() {
        return ExchangeBuilder
                .topicExchange(EXPIRE_EXCHANGE)
                .durable(true)
                .build();
    }

    // 死信过期队列
    @Bean(EXPIRE_QUEUE)
    public Queue expireQueue() {
        return QueueBuilder
                .durable(EXPIRE_QUEUE)
                .build();
    }

    // 死信过期交换机和队列进行绑定
    @Bean
    public Binding bindExpireExchangeQueue(@Qualifier(EXPIRE_EXCHANGE) Exchange exchange,@Qualifier(EXPIRE_QUEUE) Queue queue) {
        return BindingBuilder
                .bind(queue)
                .to(exchange)
                .with("#.expire_orderRouting.#")
                .noargs();
    }

    // 正常订单交换机
    @Bean(ORDER_EXCHANGE)
    public Exchange orderExchange() {
        return ExchangeBuilder
                .topicExchange(ORDER_EXCHANGE)
                .durable(true)
                .build();
    }

    // 正常订单队列
    @Bean(ORDER_QUEUE)
    public Queue orderQueue() {
        return QueueBuilder
                .durable(ORDER_QUEUE)
                .ttl(15000) // 正常队列消息存活时间模拟订单 30分钟为 10秒
                .deadLetterExchange(EXPIRE_EXCHANGE)    // 绑定死信过期交换机
                .deadLetterRoutingKey("expire_orderRouting")    // 绑定死信过期交换机的路由关键字
                .build();

    }

    // 正常订单交换机和队列绑定
    @Bean
    public Binding bindExchangeQueue(@Qualifier(ORDER_EXCHANGE) Exchange exchange, @Qualifier(ORDER_QUEUE) Queue queue) {
        return BindingBuilder
                .bind(queue)
                .to(exchange)
                .with("#.orderRouting.#")
                .noargs();
    }
}
